package com.patsnap.data.npd.dw.common.compress;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ByteBufferBase64Adapter implements JsonSerializer<ByteBuffer>, JsonDeserializer<ByteBuffer> {
    
    private static final String SPLIT_SYMBOL = ",";
    
    public ByteBuffer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
        try {
            String text = json.getAsString();
            byte[] bytes = Base64.getDecoder().decode(text);
            return ByteBuffer.wrap(bytes);

//            if (StringUtils.contains(text, SPLIT_SYMBOL)) {
//                return convertString2Bytes(json.getAsString());
//            }
//            else {
//
//                byte[] bytes = Base64.getDecoder().decode(text);
//                return ByteBuffer.wrap(bytes);
//
////                byte[] buff = Base64Utils.decodeFromString(text);
////                return ByteBuffer.wrap(buff);
//            }
        }
        catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
    
    public JsonElement serialize(ByteBuffer src, Type typeOfSrc, JsonSerializationContext context) {
        String content = null;
        try {
            byte[] bytes = new byte[src.remaining()];
            src.get(bytes);
            byte[] base64Bytes = Base64.getEncoder().encode(bytes);
            content = new String(base64Bytes, StandardCharsets.UTF_8);
            //            content = convertBytes2String(src);
//            content = Base64Utils.encodeToString(src.array());
            return new JsonPrimitive(content);
        }
        catch (Exception e) {
        }
        return null;
    }
    
    private String convertBytes2String(ByteBuffer src) {
        StringBuilder sb = new StringBuilder();
        for (byte b : src.array()) {
            sb.append(b).append(SPLIT_SYMBOL);
        }
        return sb.toString();
    }
    
//    private ByteBuffer convertString2Bytes(String string)
//        throws Exception {
//        StringReader reader = new StringReader(string);
//        int vInteger = -1;
//        ByteArrayBuilder buffer = new ByteArrayBuilder();
//        StringBuilder sb = new StringBuilder();
//        char ch = SPLIT_SYMBOL.charAt(0);
//        while ((vInteger = reader.read()) != -1) {
//            char c = (char)vInteger;
//            if (c == ch) {
//                //append to buffer
//                buffer.append(Byte.valueOf(sb.toString()));
//                sb.setLength(0);
//            }
//            else {
//                sb.append(c);
//            }
//        }
//        //last sb
//        if (sb.length() > 0) {
//            buffer.append(Byte.valueOf(sb.toString()));
//        }
//        buffer.close();
//        return ByteBuffer.wrap(buffer.toByteArray());
//    }
}
